package by.bsu.rfe.belianko.euniversity.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import by.bsu.rfe.belianko.euniversity.controller.command.Command;
import by.bsu.rfe.belianko.euniversity.controller.helper.RequestHelper;
import by.bsu.rfe.belianko.euniversity.exceptions.CommandException;
import by.bsu.rfe.belianko.euniversity.pool.ConnectionPool;

/**
 * Controller of application. Implements front-controller and command pattern.
 * 
 * @author Vitali_Belianko
 * 
 */
public final class MainController extends HttpServlet {
	private static final RequestHelper requestHelper = RequestHelper.getInstance();
	private static final String WEB_INF_PAGES = "/WEB-INF/pages/";
	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = Logger.getLogger(MainController.class);

	public MainController() {
		super();
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);

	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		processRequest(request, response);

	}
	
	/**
	 * Create command by request parameter and execute the page
	 * 
	 * @param request - HttpServletRequest
	 * @param response - HttpServletResponse
	 * 
	 * @throws ServletException
	 * @throws IOException
	 */
	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		String page = null;

		Command cmdHelper = requestHelper.getCommand(request);

		try {
			page = cmdHelper.execute(request);
		} catch (CommandException e) {
			LOGGER.error(e.getMessage());
			throw new ServletException();
		}
		dispatch(request, response, page);

	}
	/**
	 * Send forward to the page
	 * 
	 * @param request - HttpServletRequest
	 * @param response - HttpServletResponse
	 * @param page - page where should send forward
	 * 
	 * @throws ServletException
	 * @throws IOException
	 */
	private void dispatch(HttpServletRequest request, HttpServletResponse response, String page)
			throws ServletException, IOException {

		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(WEB_INF_PAGES + page);
		dispatcher.forward(request, response);

	}

	@Override
	public void destroy() {
		super.destroy();
		ConnectionPool.close();

	}

}
